import logging
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
import time

from app.config import settings
from app.storage.json_storage import storage
from app.models.simple_schemas import APIResponse

# 配置日志
logging.basicConfig(
    level=getattr(logging, settings.LOG_LEVEL.upper()),
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

logger = logging.getLogger(__name__)

@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理 - 简化版本"""
    # 启动时初始化
    logger.info("JSON storage initialized successfully")
    logger.info("Application started in SIMPLE mode")
    
    yield
    
    # 关闭时清理
    logger.info("Application shutdown")

# 创建FastAPI应用
app = FastAPI(
    title="Crawl4AI 任务管理系统 - 简化版",
    description="基于JSON文件存储的简化爬虫任务管理系统",
    version="1.0.0-simple",
    lifespan=lifespan,
    docs_url="/api/docs",
    redoc_url="/api/redoc",
    openapi_url="/api/openapi.json"
)

# CORS配置
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 简化版本允许所有来源
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 请求日志中间件
@app.middleware("http")
async def log_requests(request: Request, call_next):
    """记录请求日志"""
    start_time = time.time()
    
    # 记录请求
    logger.info(f"Request: {request.method} {request.url}")
    
    # 处理请求
    response = await call_next(request)
    
    # 记录响应
    process_time = time.time() - start_time
    logger.info(f"Response: {response.status_code} - {process_time:.3f}s")
    
    return response

# 全局异常处理
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    """全局异常处理"""
    logger.error(f"Global exception: {exc}", exc_info=True)
    
    return JSONResponse(
        status_code=500,
        content=APIResponse(
            success=False,
            message="服务器内部错误",
            error_code="INTERNAL_ERROR"
        ).model_dump()
    )

# 导入路由
from app.routers import auth_simple as auth
from app.routers import tasks_simple as tasks

# 注册路由
app.include_router(auth.router, prefix="/api/v1/auth", tags=["认证"])
app.include_router(tasks.router, prefix="/api/v1/tasks", tags=["任务管理"])

# 根路径
@app.get("/", response_model=APIResponse[dict])
def read_root():
    """根路径 - 系统信息"""
    return APIResponse(
        message="Crawl4AI 任务管理系统 - 简化版",
        data={
            "name": "Crawl4AI Task Manager - Simple",
            "version": "1.0.0-simple",
            "description": "基于JSON文件存储的简化爬虫任务管理系统",
            "features": [
                "用户认证（简化版）",
                "任务管理（CRUD操作）",
                "JSON文件存储",
                "模拟爬虫执行",
                "基本日志记录"
            ],
            "api_docs": "/api/docs",
            "storage_type": "JSON Files"
        }
    )

# 健康检查
@app.get("/api/v1/health", response_model=APIResponse[dict])
def health_check():
    """健康检查"""
    try:
        # 检查存储状态
        import os
        data_dir_exists = os.path.exists("data")
        data_files = {
            "users.json": os.path.exists("data/users.json"),
            "tasks.json": os.path.exists("data/tasks.json"),
            "sessions.json": os.path.exists("data/sessions.json"),
            "logs.json": os.path.exists("data/logs.json")
        }
        
        health_data = {
            "status": "healthy",
            "storage_type": "JSON Files",
            "data_directory": data_dir_exists,
            "data_files": data_files,
            "mode": "simple"
        }
        
        return APIResponse(
            message="系统健康",
            data=health_data
        )
        
    except Exception as e:
        logger.error(f"Health check error: {e}")
        return APIResponse(
            success=False,
            message="系统异常",
            data={"error": str(e)}
        )

# 系统统计
@app.get("/api/v1/stats", response_model=APIResponse[dict])
def get_system_stats():
    """获取系统统计信息"""
    try:
        # 获取基本统计
        users = storage.get_users()
        tasks = storage.get_tasks()
        
        # 任务状态统计
        task_stats = {}
        for task in tasks:
            status = task.get('status', 'unknown')
            task_stats[status] = task_stats.get(status, 0) + 1
        
        stats_data = {
            "users_count": len(users),
            "tasks_count": len(tasks),
            "task_status_stats": task_stats,
            "storage_info": {
                "type": "JSON Files",
                "location": "data/"
            }
        }
        
        return APIResponse(
            message="获取统计信息成功",
            data=stats_data
        )
        
    except Exception as e:
        logger.error(f"Get stats error: {e}")
        return APIResponse(
            success=False,
            message="获取统计信息失败",
            data={"error": str(e)}
        )

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "app.main_simple:app",
        host=settings.HOST,
        port=settings.PORT,
        reload=settings.DEBUG,
        log_level=settings.LOG_LEVEL.lower()
    )
